//
//  CJAlertViewSign.m
//  NtoccShipper
//
//  Created by mac on 2020/8/31.
//  Copyright © 2020 zhuchongjin. All rights reserved.
//

#import "CJAlertViewSign.h"
//static const CGFloat AlertViewWidth = kScreenWidth - 40;
//static const CGFloat AlertViewMarginH = 20;
//static const CGFloat AlertViewVerticalElementSpace = 10;
//static const CGFloat AlertViewButtonHeight = 44;
//static const CGFloat AlertViewLineLayerWidth = 0.5;

@interface CJAlertViewSign(){
    int timeOld;
    NSTimer * _timer;
    
}
@property (strong, nonatomic) CJLabel *labTitle;
@property (nonatomic,strong) CJButton *btnAouthCode;
@property (nonatomic,strong) UITextField *fieldAouthCode;
@property (strong, nonatomic) CJButton *btnSure;
@property (strong, nonatomic) CJButton *btnCancle;
@property (nonatomic,copy) OnSureClick sureBlock;
@property (nonatomic,copy) OnCancleClick cancleBlock;
@property (nonatomic,copy) NSString *strCode;
@property (nonatomic,strong) CJView *coverView;
@end
@implementation CJAlertViewSign

+ (CJAlertViewSign *)shared {
    
    static dispatch_once_t predicate;
    
    static CJAlertViewSign *objc;
    
    dispatch_once(&predicate, ^{
        
        objc = [[CJAlertViewSign alloc] init];
        
    });
    
    return objc;
}


-(instancetype)initWithTitle:(NSString *)strTitle listTitle:(NSArray *)arrTitle listContent:(NSArray *)arrContent ClickOnSure:(OnSureClick )sureClick ClickOnCancle:(OnCancleClick )cancleClick{
    
    if (self = [super init]) {
        
        //        self.frame = CGRectMake(0, 0, kScreenWidth - 40, 400);
        //        self.backgroundColor = [UIColor cjWhiteColor];
        self.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        self.backgroundColor = [[UIColor cjBlackColor] colorWithAlphaComponent:0.3];

        [self addSubview:self.coverView];
        self.coverView.center = self.center;
        [CJUtil getViewCutAllCornRound:self.coverView height:10];

        
        [self.coverView addSubview:self.labTitle];
        self.labTitle.text = strTitle;
    
        self.strCode = arrContent[3];
        CGFloat leftMarg = 10;
        for (int i = 0; i < arrTitle.count; i ++) {
            
            UIView * liebiaoView = [[UIView alloc]initWithFrame:CGRectMake(leftMarg, self.labTitle.bottom +  + i * 50, self.coverView.width - leftMarg*2, 40)];
        
            liebiaoView.backgroundColor = [UIColor cjWhiteColor];
            [self.coverView addSubview:liebiaoView];

            UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(0, 5, 80, 40)];
            label.text = arrTitle[i];
            label.textAlignment = NSTextAlignmentLeft;
            label.font = [UIFont cjTitleFont14];
            label.textColor = [UIColor cjMainTextColor];
            [liebiaoView addSubview:label];
            

            if (i != 3) {
                
                UILabel * contentLabel = [[UILabel alloc]initWithFrame:CGRectMake(label.right, label.top, self.coverView.width -label.width - 25, 40)];
                contentLabel.text = arrContent[i];
                contentLabel.textAlignment = NSTextAlignmentRight;
                contentLabel.font = [UIFont cjTitleFont14];
                contentLabel.textColor = [UIColor cjMainTextColor];
                [liebiaoView addSubview:contentLabel];
                
                UILabel * bg = [[UILabel alloc]initWithFrame:CGRectMake(0, liebiaoView.height -1, self.width, CJLineHeight)];
                bg.backgroundColor = [UIColor cjLineColor];
                [liebiaoView addSubview:bg];
                
            }else{
                
                CJView *viewAouth = CJView.viewInit
                .viewFrame(CGRectMake(label.right, label.top, self.coverView.width - 0-label.width - 25, 40))
                .viewCornerRadius(CJUICutCorner)
                .viewBorderWidthColor(CJUICornerWidth ,[UIColor cjLineColor])
                ;
                [liebiaoView addSubview:viewAouth];
                
                
                self.fieldAouthCode = [[UITextField alloc]initWithFrame:CGRectMake(10, 0,viewAouth.width - 110 , viewAouth.height)];
                self.fieldAouthCode.font = [UIFont cjTitleFont14];
                self.fieldAouthCode.textColor = [UIColor cjMainTextColor];
                self.fieldAouthCode.placeholder = @"请填写验证码";
                [viewAouth addSubview:self.fieldAouthCode];
                
                self.btnAouthCode = CJButton.btnInit
                .btnFrame(CGRectMake(self.fieldAouthCode.right, 0, viewAouth.width - 20 - self.fieldAouthCode.width, viewAouth.height))
                .btnNormalTitleColor([UIColor cjMainColorText])
                .btnSelectTitleColor([UIColor cjMainColorText])
                .btnText(@"获取验证码")
                .btnTargetAction(self,@selector(btnGetAouthCodeAction:))
                ;
                [viewAouth addSubview:self.btnAouthCode];

            }

        }

        
        [self.coverView addSubview:self.btnCancle];
        [self.coverView addSubview:self.btnSure];
        
        self.sureBlock = sureClick;
        self.cancleBlock = cancleClick;
        
    }
    [self show];
    return self;
}

- (void)btnGetAouthCodeAction:(CJButton *)sender{
    
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tps-api/elecSign/sendSms",CJBaseUrl);
    NSDictionary *dicPar = @{
                             @"code":self.strCode,
    };
    
    @weakify(self);
    [[HDNetworking sharedHDNetworking] PUTWithSign:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
        
        @strongify(self);
//        DLog(@"++++++++%@",responseObject);
        NSString *status = CJStringWithFormat(@"%@",responseObject[@"status"]);
        NSString *msg = responseObject[@"msg"];
        //        DLog(@"status============== %@",status);
        if (status.intValue == 0) {
            self.btnAouthCode.userInteractionEnabled = NO;
            timeOld = 60;
            [self startTimer];
        }else{
            WLAlertView * alerView =(WLAlertView *)[self superview];
            [alerView dismissAnimated:YES];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [CJAlert showStringDismissWithDelay:msg];
            });
        }

    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        
    }];

}

- (void)startTimer{
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireOdlM) userInfo:nil repeats:YES];
}

- (void)stopTimer{
    
    if (_timer == nil) {
        return;
    }
    [_timer invalidate];
    _timer = nil;
}

- (void)dealloc{
    
   NSLog(@"%s",__func__);
    [_timer invalidate];
    _timer = nil;
}

- (void)timerFireOdlM{
    
    NSString * str =[NSString stringWithFormat:@"(%ds)",timeOld];
//    [self.btnGetCode setTitle:str forState:UIControlStateNormal];
    [self.btnAouthCode setTitle:str forState:UIControlStateNormal];
    timeOld--;
    if (timeOld==0) {
        [self stopTimer];
        timeOld=60;
        [self.btnAouthCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.btnAouthCode setTitle:@"获取验证码" forState:UIControlStateSelected];
        self.btnAouthCode.userInteractionEnabled = YES;
        
    }
}


- (void)btnClickSureAction:(CJButton *)sender{
    
 
    if (![CJRegular getDealCode:[CJControl getThreeUnaryValueStr:self.fieldAouthCode.text]]) {
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [CJAlert showStringDismissWithDelay:@"请填写正确的验证码"];
        });
        
    }else{

        NSString *strURL = CJStringWithFormat(@"%@/ntocc-tps-api/elecSign/eSign",CJBaseUrl);
        NSDictionary *dicPar = @{
                                 @"code":self.strCode,
                                 @"smsCode":self.fieldAouthCode.text
        };
        
        @weakify(self);
        [[HDNetworking sharedHDNetworking] PUT:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
            
            @strongify(self);
            [self hidden];
            DLog(@"++++++++%@",responseObject);
            if (self.sureBlock) {
                self.sureBlock(@"");
            }
            
        } failure:^(NSError * _Nonnull error) {
            DLog(@"++++++++%@",error);
            
        }];

    }

//    [alerView dismissAnimated:YES];
}
- (void)btnClickCancleAction:(CJButton *)sender{
    
    if (self.cancleBlock) {
        self.cancleBlock(@"");
    }
    [self hidden];
}


/// 展示隐藏
- (void)show {
    [[UIApplication sharedApplication].keyWindow addSubview:self];
//    _titleLabel.text = _title;
//    _msgLabel.text = _message;
    self.center = [UIApplication sharedApplication].keyWindow.center;
    [UIView animateWithDuration:0.5 animations:^{
        self.alpha = 1.0;
    }];
}

- (void)hidden {
    
    @weakify(self);
    [UIView animateWithDuration:0.5 animations:^{
        
        @strongify(self);
        self.alpha = 0.0;
        [self stopTimer];
        timeOld=60;
        [self.btnAouthCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        [self.btnAouthCode setTitle:@"获取验证码" forState:UIControlStateSelected];
        self.btnAouthCode.userInteractionEnabled = YES;
    }];
}


- (CJView *)coverView{
    if (!_coverView) {
        _coverView =CJView.viewInit
        .viewFrame(CGRectMake(0, 0,kScreenWidth - 40, 380))
        .viewbgColor([UIColor cjWhiteColor])
        ;
//        _coverView.alpha = 0.3;
    }
    return _coverView;
}


/**
 *  标题、内容动态行高的计算
 *
 *  @return CGRect
 */
- (CGRect)adjustLabelFrameHeight:(UILabel *)label
{
    CGFloat height;
    
    if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1) {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        CGSize size = [label.text sizeWithFont:label.font
                             constrainedToSize:CGSizeMake(label.frame.size.width, FLT_MAX)
                                 lineBreakMode:NSLineBreakByWordWrapping];
        
        height = size.height;
#pragma clang diagnostic pop
    } else {
        NSStringDrawingContext *context = [[NSStringDrawingContext alloc] init];
        context.minimumScaleFactor = 1.0;
        CGRect bounds = [label.text boundingRectWithSize:CGSizeMake(label.frame.size.width, FLT_MAX)
                                                 options:NSStringDrawingUsesLineFragmentOrigin
                                              attributes:@{NSFontAttributeName:label.font}
                                                 context:context];
        height = bounds.size.height;
    }
    
    return CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width,label.text.length?height:0);
}

#pragma mark ----------lazy




- (CJLabel *)labTitle{
    if (!_labTitle) {

        _labTitle = CJLabel.labInit
        .labFrame(CGRectMake(0,0, self.width, 60))
//        .labFontSize(18)
        .labFont([UIFont boldSystemFontOfSize:18])
        .labAlignment(NSTextAlignmentCenter)
        .labTextColor(CJRGB16Color(0x444D68))
        .labAdjustsFontSizeToFitWidth(YES)
        ;
    }
    return _labTitle;
}
- (CJButton *)btnCancle{

    if (!_btnCancle) {
        _btnCancle = CJButton.btnInit
        .btnFrame(CGRectMake(20, 300, (self.coverView.width - 60)/2,35))
        .btnText(@"取消")
        .btnFontSize(15)
        .btnBgColor([UIColor cjWhiteColor])
        .btnCornerWidth(0.5)
        .btnCornerRadius(5)
        .btnCornerColor([UIColor cjMainColor])
        .btnNormalTitleColor([UIColor cjMainColor])
        .btnTargetAction(self,@selector(btnClickCancleAction:))

        ;
    }
    return _btnCancle;
}

- (CJButton *)btnSure{

    if (!_btnSure) {
        _btnSure = CJButton.btnInit
        .btnFrame(CGRectMake(self.btnCancle.right + 20, self.btnCancle.top, self.btnCancle.width,self.btnCancle.height ))
        .btnText(@"确定")
        .btnFontSize(15)
        .btnBgColor([UIColor cjMainColor])
//        .btnCornerWidth(0.5)
        .btnCornerRadius(5)
        .btnNormalTitleColor([UIColor cjWhiteColor])
        .btnTargetAction(self,@selector(btnClickSureAction:))
        ;
    }
    return _btnSure;
}
@end

